package com.qingcloud.adminbackend.controller;


import cn.hutool.core.util.IdUtil;
import com.qingcloud.adminbackend.anno.SysApi;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.base.ZTreeBo;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.role.SysRole;
import com.qingcloud.adminbackend.entity.sysfunction.FunctionPageRequest;
import com.qingcloud.adminbackend.entity.sysfunction.SysFunction;
import com.qingcloud.adminbackend.service.ISysFunctionService;
import com.qingcloud.adminbackend.utils.CommonUtil;
import com.qingcloud.base.annotation.LoginUser;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SysFunctionController
 * @Description 功能模块管理
 * @Author qym
 * @Date 2021/3/23 上午9:38
 **/
@Api(value = "模块管理相关API", description = "模块管理相关API")
@RestController
@RequestMapping("/function")
public class SysFunctionController {

    public static final String webCtx = "/weather-web";

    public static final String surveyWebCtx = "/survey-web";
    @Resource
    private ISysFunctionService sysFunctionService;

    @SysApi
    @ApiOperation(value = "菜单功能分页查询", notes = "菜单功能分页查询", response = SysFunction.class)
    @PostMapping(value = "/getFunctionsPage")
    public Map<String, Object> getFunctionsPage(FunctionPageRequest functionPageRequest, HttpServletRequest request ,@LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin()==1?true:false;
        return sysFunctionService.getSysFunctionsPage(userId, isAdmin, functionPageRequest);
    }

    @SysApi
    @ApiOperation(value = "新增菜单功能", notes = "新增菜单功能")
    @PostMapping("/addSysFunction")
    public AjaxResult addSysFunction(@RequestBody SysFunction sysFunctionDTO, HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        sysFunctionDTO.setCreateBy(userId);
        Map<String, SysFunction> result = sysFunctionService.addFunction(sysFunctionDTO);
        SysFunction sf = result.get("function");
        return new AjaxResult(WamingConstant.SUCCESS, "添加成功", sf);
    }

    @SysApi
    @ApiOperation(value = "通过ID获取菜单功能", notes = "通过ID获取菜单功能", response = SysFunction.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "functionId", value = "功能ID", required = true, dataType = "string", paramType = "path", defaultValue = "8ef178f99a4f4c01a94b51ca92bca0a6"),
    })
    @PostMapping(value = "findById/{functionId}")
    public AjaxResult findById(@PathVariable String functionId) {
        return new AjaxResult(WamingConstant.SUCCESS, null, sysFunctionService.findById(functionId));
    }


    @SysApi
    @ApiOperation(value = "修改菜单功能", notes = "修改菜单功能", response = SysFunction.class)
    @PostMapping("/updateSysFunction")
    public AjaxResult updateSysFunction(@RequestBody SysFunction sysFunctionDTO, HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        sysFunctionDTO.setModifyBy(userId);
        Map<String, SysFunction> result = sysFunctionService.updateFunction(sysFunctionDTO);
        SysFunction sf = result.get("function");
        return new AjaxResult(WamingConstant.SUCCESS, "修改成功", sf);
    }

    @ApiOperation(value = "取得角色菜单的Id信息", notes = "取得角色菜单的Id信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "string", paramType = "path", defaultValue = "8ef178f99a4f4c01a94b51ca92bca0a6"),
    })
    @GetMapping(value = "/queryRoleFunIds/{roleId}")
    public AjaxResult queryFunIds(@PathVariable("roleId") String roleId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        List<SysFunction> funs = sysFunctionService.getFunsByRoleId(roleId);
        if (CommonUtil.checkList(funs)) {
            List<String> list = new ArrayList<String>();
            for (SysFunction sysFunctionDTO : funs) {
                list.add(sysFunctionDTO.getId());
            }
            result.put("funIds", list);
        }
        return new AjaxResult(WamingConstant.SUCCESS, "", result);
    }

    @ApiOperation(value = "获取当前登录用户功能模块tree结构", notes = "获取当前登录用户功能模块tree结构", response = ZTreeBo.class)
    @PostMapping(value = "/getFunctionsTree")
    public AjaxResult getFunctionsTree(HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        String loginUserId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin()==1?true:false;

        return new AjaxResult(WamingConstant.SUCCESS, "获取成功", sysFunctionService.getFunctionsTree(isAdmin, loginUserId));
    }

    @SysApi
    @ApiOperation(value = "获取当前登录用户功能模块tree结构", notes = "获取当前登录用户功能模块tree结构", response = ZTreeBo.class)
    @GetMapping(value = "/getFunctionsTreeV2")
    public AjaxResult getFunctionsTreeV2(@RequestParam(value = "menuType", required = false) Integer menuType) {
        return new AjaxResult(WamingConstant.SUCCESS, "获取成功", sysFunctionService.getFunctionsTreeV2(menuType));
    }

    @SysApi
    @ApiOperation(value = "删除功能权限", notes = "删除功能权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "functionIds", value = "功能ID字符串", dataType = "string", paramType = "path", required = true,
                    defaultValue = "4028f481585db7d701585dc9f8a0001233"),
    })
    @CacheEvict(value = "func", key = "#functionIds")
    @PostMapping(value = "/delete/{functionIds}")
    public AjaxResult delete(@PathVariable String functionIds, HttpServletRequest request) {
        String[] listIds = functionIds.split(",");
        if(listIds!=null && listIds.length>0) {
            for (int i = 0; i < listIds.length; i++) {
                sysFunctionService.deleteFunction(listIds[i]);
            }
        }
        return new AjaxResult(WamingConstant.FAILURE, "部分功能存在子功能无法全部删除", null);
    }

    @ApiOperation(value = "通过CODE统计模块数量", notes = "通过CODE统计模块数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "模块编号", dataType = "string", paramType = "query",
                    required = true, defaultValue = "ROLE_FUN_001"),
            @ApiImplicitParam(name = "ignoreId", value = "不计算的模块ID", dataType = "string", paramType = "query", defaultValue = "123213123"),
    })
    @PostMapping("/getCountByCode")
    public AjaxResult getCountByCode(@RequestParam("code") String code,
                                     @RequestParam(name = "ignoreId", required = false) String ignoreId) {
        return new AjaxResult(WamingConstant.SUCCESS, null, sysFunctionService.getCountByCode(code, ignoreId));
    }

    @ApiOperation(value = "通过父模块ID获取模块信息", notes = "通过父模块ID获取模块信息", response = ZTreeBo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "父模块编号", dataType = "string", paramType = "query",
                    required = true, defaultValue = "ROLE_FUN_001")
    })
    @PostMapping(value = "/getFunctionsByParentID")
    public Object getFunctionsByParentID(String parentId, HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        String loginUserId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin()==1?true:false;
        return sysFunctionService.getFunctionsByParentID(parentId, loginUserId, isAdmin);
    }

    @ApiOperation(value = "功能模块关系处理", notes = "功能模块关系处理", response = SysRole.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "funId", value = "功能模块ID", dataType = "string", paramType = "query",
                    required = true, defaultValue = "12312312312")
    })
    @GetMapping("/getFunRelation")
    public AjaxResult getFunRelation(String funId) {
        return new AjaxResult(WamingConstant.SUCCESS, null, sysFunctionService.getFunRelation(funId));
    }

    @SysApi
    @ApiOperation(value = "更新功能排序", notes = "更新功能排序")
    @PostMapping("/updateOrderNo")
    public AjaxResult updateOrderNo(@RequestBody SysFunction.RequestOrderParam requestOrderParam, HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        String loginUserId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin()==1?true:false;
        sysFunctionService.updateOrderNo(requestOrderParam, loginUserId);
        return new AjaxResult(WamingConstant.SUCCESS, "更新成功", null);
    }

    @SysApi
    @ApiOperation(value = "更新删除标识", notes = "更新删除标识")
    @PostMapping("/enableOrDisable")
    public AjaxResult enableOrDisable(@RequestBody SysFunction.RequestEnableParam requestEnableParam, HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        String loginUserId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin()==1?true:false;
        sysFunctionService.enableOrDisable(requestEnableParam, loginUserId);
        return new AjaxResult(WamingConstant.SUCCESS, "更新成功", null);
    }
}

